package com.albertyjz.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//题目：两个线程，操作初始值为0的一个变量，一个加1一个减1来10轮让最后的值还是0。
// 这样是没问题的，但是当两个线程加，两个线程减，就有概率报错，最后的值不是0，只能用while，不能if。
class AirConditioner{
    private int num=0;
    private Lock lock=new ReentrantLock();
    private Condition condition=lock.newCondition();

    public void increment() throws InterruptedException {
        lock.lock();

        try {
            while (num!=0) {
                condition.await();
            }
                num++;
                System.out.println(Thread.currentThread().getName()+"\t"+num);
                condition.signalAll();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public synchronized void decrement() throws InterruptedException {
        lock.lock();

        try {
            while (num==0) {
                condition.await();
            }
            num--;
            System.out.println(Thread.currentThread().getName()+"\t"+num);
            condition.signalAll();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
public class ThreadWaitNotifyDemo {
    public static void main(String[] args) throws Exception {
        AirConditioner airConditioner=new AirConditioner();
        new Thread(()->{
            for (int i = 1; i <= 1000; i++) {
                try {
                    airConditioner.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"a").start();
        new Thread(()->{
            for (int i = 1; i <= 1000; i++) {
                try {
                    airConditioner.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"b").start();
        new Thread(()->{
            for (int i = 1; i <= 1000; i++) {
                try {
                    airConditioner.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"c").start();
        new Thread(()->{
            for (int i = 1; i <= 1000; i++) {
                try {
                    airConditioner.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"d").start();
    }
}
